﻿Public Class FrmAlquiler
    Dim acceso As New acceso_a_datos

    Private Sub mtxtNroDoc_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles mtxtNroDoc.KeyUp
        If e.KeyCode = Keys.Enter Then
            If txtApellidos.Text = "" Then
                MyBase.limpiarCamposArticulo()
                MyBase.limpiarCliente()
                borrarComboEjemplares()
                mtxtCodBarrasArticulo.Enabled = False
                btnFinalizarAlquiler.Enabled = False
                rdbCodigoBarrasArticulo.Checked = True
                rdbCodigoBarrasArticulo.Enabled = False
                rdbTituloArticulo.Enabled = False
                mtxtNroDoc.Focus()
            Else
                mtxtCodBarrasArticulo.Enabled = True
                rdbCodigoBarrasArticulo.Enabled = True
                rdbTituloArticulo.Enabled = True
                If DataGridViewAlquiler.Rows.Count > 0 Then
                    btnFinalizarAlquiler.Enabled = True
                End If
                mtxtCodBarrasArticulo.Focus()
            End If
        End If
    End Sub

    Private Sub mtxtCodBarrasArticulo_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles mtxtCodBarrasArticulo.KeyUp, cmbTituloArticulo.KeyUp
        If e.KeyCode = Keys.Enter Then
            If Not txtCantidadDisponible.Text = "" Then
                Dim cantidad As Integer = acceso._consulta("SELECT COUNT(*) FROM Ejemplar WHERE disponible=1 AND idArticulo=" & tablaArticulo.Rows(0)("idArticulo")).Rows(0)(0)
                txtPrecio.Text = MyBase.tablaArticulo(0)("precioAlquiler")
                txtSubTotal.Text = txtPrecio.Text
                If cantidad > 0 Then
                    Dim tablaEjemplares As DataTable = acceso._consulta("SELECT idEjemplar FROM Ejemplar WHERE disponible=1 AND idArticulo=" & tablaArticulo.Rows(0)("idArticulo"))
                    For Each fila As DataRow In tablaEjemplares.Rows
                        Dim agregar As Boolean = True
                        For Each filaGrilla As DataGridViewRow In DataGridViewAlquiler.Rows
                            If filaGrilla.Cells("colIdArticulo").Value.Equals(tablaArticulo(0)(0)) Then
                                If filaGrilla.Cells("colEjemplar").Value = fila(0) Then
                                    cantidad -= 1
                                    agregar = False
                                End If
                            End If
                        Next
                        If agregar Then
                            cmbEjemplaresDisponibles.Items.Add(fila(0))
                        End If
                    Next
                    txtCantidadDisponible.Text = cantidad
                    If cantidad > 0 Then
                        cmbEjemplaresDisponibles.Enabled = True
                        cmbEjemplaresDisponibles.SelectedIndex = 0
                        cmbEjemplaresDisponibles.Focus()
                        txtCantidadVenta.Text = 1
                        btnAgregar.Enabled = True
                    End If
                End If
            End If
        Else
            borrarComboEjemplares()
            btnAgregar.Enabled = False
        End If
    End Sub

    Private Sub btnAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregar.Click
        DataGridViewAlquiler.Rows.Add(tablaArticulo.Rows(0)("idarticulo"), tablaArticulo.Rows(0)("nombre"), cmbEjemplaresDisponibles.Text, tablaArticulo.Rows(0)("precioAlquiler"))
        borrarComboEjemplares()
        btnAgregar.Enabled = False
        btnFinalizarAlquiler.Enabled = True
        btnCancelar.Enabled = True
    End Sub


    Private Sub DataGridViewAlquiler_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles DataGridViewAlquiler.RowsAdded
        cmbEjemplaresDisponibles.Items.Remove(cmbEjemplaresDisponibles.SelectedItem)
        calcularTotalAlquiler()
        btnFinVta.Enabled = False
    End Sub


    Private Sub DataGridViewAlquiler_RowsRemoved(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles DataGridViewAlquiler.RowsRemoved
        If DataGridViewDatos.Rows.Count > 0 Then
            calcularTotalAlquiler()
        Else
            txtTotal.Text = 0
            btnFinalizarAlquiler.Enabled = False
            btnCancelar.Enabled = False
        End If
        limpiarCamposArticulo()
    End Sub

    Private Sub calcularTotalAlquiler()
        Dim total As Double = 0
        For Each fila As DataGridViewRow In DataGridViewAlquiler.Rows
            total += fila.Cells("colSubTotal").Value
        Next
        txtTotal.Text = total
    End Sub

    Private Sub btnFinalizarAlquiler_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFinalizarAlquiler.Click
        MsgBox("Total A Cobrar: $ " & txtTotal.Text, MsgBoxStyle.Information, "Total")

        acceso._tabla = "Alquiler"
        Dim consultaExisteAlquiler As String = "SELECT * FROM Alquiler WHERE Fecha =  GetDate() AND idTipoDNI=" & cmbTipoDoc.SelectedValue & " AND NroDNI=" & mtxtNroDoc.Text
        Dim tabla As DataTable = acceso._consulta(consultaExisteAlquiler)
        If tabla.Rows.Count = 0 Then
            Dim consultaInsertAlquiler As String = "INSERT INTO Alquiler(Fecha, idTipoDNI, NroDNI, legajo) VALUES(GetDate()," & cmbTipoDoc.SelectedValue & ", " & mtxtNroDoc.Text & ", " & cmbVendedor.SelectedValue & ")"
            acceso._consulta(consultaInsertAlquiler)
        End If

        acceso._tabla = "DetalleAlquiler"
        For Each fila As DataGridViewRow In DataGridViewAlquiler.Rows
            Dim consultaInsertDetalleVenta As String = "INSERT INTO DetalleAlquiler(Fecha, idTipoDNI, NroDNI, idEjemplar, idArticulo, Precio, FechaDevoluPrevista) VALUES('" & Date.Today & "', " & cmbTipoDoc.SelectedValue & ", " & mtxtNroDoc.Text & ", " & fila.Cells(2).Value & ", " & fila.Cells(0).Value & ", " & fila.Cells(3).Value.ToString.Replace(",", ".") & ", " & calcularFechaDevolucion(fila.Cells(0).Value) & ")"
            acceso._consulta(consultaInsertDetalleVenta)
            Dim consultaUpdateEjemplar As String = "UPDATE Ejemplar SET Disponible = 'False' WHERE idarticulo = " & fila.Cells(0).Value & " AND idEjemplar = " & fila.Cells(2).Value
            acceso._consulta(consultaUpdateEjemplar)
        Next
        MsgBox("Se registró el alquiler exitosamente", MsgBoxStyle.Exclamation, "Alquiler Registrado")
        MyBase.limpiarCamposArticulo()
        MyBase.limpiarCliente()
        borrarComboEjemplares()
        borrarGrillaAlquiler()
        btnFinalizarAlquiler.Enabled = False
        btnCancelar.Enabled = False
        cmbTituloArticulo.Enabled = False
        rdbCodigoBarrasArticulo.Checked = True
        rdbCodigoBarrasArticulo.Enabled = False
        rdbTituloArticulo.Enabled = False
        mtxtCodBarrasArticulo.Enabled = False
        mtxtNroDoc.Focus()
    End Sub

    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        MyBase.limpiarCamposArticulo()
        MyBase.limpiarCliente()
        borrarComboEjemplares()
        borrarGrillaAlquiler()
        rdbCodigoBarrasArticulo.Checked = True
        mtxtCodBarrasArticulo.Enabled = False
        btnFinalizarAlquiler.Enabled = False
        rdbCodigoBarrasArticulo.Enabled = False
        rdbTituloArticulo.Enabled = False
        mtxtNroDoc.Focus()
    End Sub

    Private Sub borrarComboEjemplares()
        cmbEjemplaresDisponibles.Items.Clear()
        cmbEjemplaresDisponibles.SelectedItem = -1
        cmbEjemplaresDisponibles.Enabled = False
    End Sub

    Private Function calcularFechaDevolucion(ByVal idArticulo As Integer) As Date
        Dim consultaFechaDevolucion As String = "SELECT t.DiasPrestamo FROM TipoArticulo t, Articulo a WHERE a.idTipoArticulo = t.idTipoArticulo AND a.idarticulo =" & idArticulo
        Return DateAdd(DateInterval.Day, acceso._consulta(consultaFechaDevolucion).Rows(0)(0), Date.Today)
    End Function

    Private Sub borrarGrillaAlquiler()
        DataGridViewAlquiler.Rows.Clear()
        'DataGridViewAlquiler.Enabled = False
    End Sub
End Class
